package com.sofwin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.sofwin.Constants;
import com.sofwin.dto.TreeNodeDto;
import com.sofwin.pojo.SRole;
import com.sofwin.pojo.SRoleResource;
import com.sofwin.service.ResourceService;
import com.sofwin.service.RoleService;

@Controller
@RequestMapping("/system/role")
public class RoleController {
	@Autowired
	private RoleService roleService;
	@Autowired
	private ResourceService resourceService;
	@RequestMapping("data")
	public String toData(Model model,SRole role,@RequestParam(required=true,defaultValue="1") Integer pageNumber,@RequestParam(required=true,defaultValue=Constants.PAGE_SIZE) Integer pageSize) {
		PageInfo<SRole> page = roleService.selectByPage(role,pageNumber,pageSize);
		model.addAttribute("page", page);
		model.addAttribute("role", role);
		return "role/data";
	}
	@RequestMapping("permission")
	public String toPermission(Model model,Integer roleId) throws JsonProcessingException {
		List<TreeNodeDto> result = resourceService.selectRoleResource(roleId);
		ObjectMapper mapper = new ObjectMapper();
		String str = mapper.writeValueAsString(result);
		model.addAttribute("str", str);
		model.addAttribute("roleId", roleId);
		return "role/permission";
	}
	
	@RequestMapping("savePermission")
	@ResponseBody
	public Map savePermission(SRoleResource roleResource) {
		Boolean status = roleService.savePermission(roleResource);
		Map map = new HashMap();
		map.put("status", status);
		return map;
	}

}
